// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package file

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"audio-server/internal/svc"
	"audio-server/internal/types"
	"context"
	"encoding/json"

	"github.com/zeromicro/go-zero/core/logx"
)

type FilePageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFilePageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilePageLogic {
	return &FilePageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FilePageLogic) FilePage(req *types.FilePageReq) (resp *types.FilePageResp, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	pageNum := req.PageNum
	if pageNum <= 0 {
		pageNum = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 10
	}
	offset := (pageNum - 1) * pageSize

	fileModel := model.NewSysFileModel(l.svcCtx.Conn)
	fileType := req.FileType

	var fileTypeList []string

	// 全部
	if fileType == "0" {
		fileTypeList = nil
		//图片
	} else if fileType == "1" {
		fileTypeList = sqlutil.ImageTypeList()
		//视频
	} else if fileType == "2" {
		fileTypeList = sqlutil.VideoTypeList()
		//音频
	} else if fileType == "3" {
		fileTypeList = sqlutil.AudioTypeList()
	}

	fileList, err := fileModel.FindUserPage(l.ctx, offset, pageSize, userId, fileTypeList, int64(req.ParentId))

	var result []types.FileRes
	for _, file := range fileList {
		tags := sqlutil.NullStringToString(file.Tags)

		userRes := types.FileRes{
			FileId:     file.FileId,
			Name:       file.Name,
			ParentId:   file.ParentId,
			ExtendName: sqlutil.NullStringToString(file.ExtendName),
			Size:       float64(file.Size),
			UpdateTime: file.UpdateTime.Format("2006-01-02 15:04:05"),
			IsDir:      sqlutil.NullInt64ToInt(file.IsDir),
			Src:        sqlutil.NullStringToString(file.Src),
		}
		var strSlice []string
		if tags != "" {
			err := json.Unmarshal([]byte(tags), &strSlice)
			if err == nil {
				if len(strSlice) != 0 {
					userRes.Tags = strSlice

				}
			}

		}

		result = append(result, userRes)
	}
	if err != nil {
		return nil, err
	}
	if result == nil {
		result = []types.FileRes{}
	}
	count, err := fileModel.FindUserCount(l.ctx, userId, fileTypeList, int64(req.ParentId))
	return &types.FilePageResp{Total: count, List: result}, nil
}
